/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.generators;

import org.jetbrains.annotations.NotNull;
import com.softwarecraftsmen.functors.*;
import com.softwarecraftsmen.functors.Boolean;

public class WhereGenerator<V> extends AbstractGenerator<V>
{
	private final Generator<V> generator;
	private final UnaryReturningFunctor<V, Boolean> whereFunctor;

	public WhereGenerator(final @NotNull Generator<V> generator, final @NotNull UnaryReturningFunctor<V, Boolean> whereFunctor)
	{
		this.generator = generator;
		this.whereFunctor = whereFunctor;
	}

	@NotNull
	public Optional<V> next()
	{
		Optional<V> nextValue;
		do
		{
			nextValue = generator.next();
			if (nextValue.isNothing().isTrue())
			{
				return nextValue;
			}
		}
		while (whereFunctor.closure(nextValue.value()).isFalse());
		return nextValue;
	}
}
